<?php
  // S'assure que l'utilisateur est loggé (sinon, expédié en page d'accueil)
  gatekeeper();

  // S'assure que l'action est sécurisée
  action_gatekeeper();
  
  $data = get_input('content');

  if(get_input('title') && get_input('description')) {
    $title = get_input('title');
    $description = get_input('description');
  }
  if(get_input('guid')) {
    $guid = get_input('guid');
  }
  $access = get_input('access_id');
  
  // Cache to the session
  $_SESSION['referentialData'] = $data;
  
  $response = array();
  
  if (isset($title) && isset($description) && !isset($guid)){
    // Initialise a new ElggObject
    $referential = new ElggObject();
    // Tell the system it's a blog post
    $referential->subtype = "referential";
    // Set its owner to the current user
    $referential->owner_guid = $_SESSION['user']->getGUID();
    // For now, set its access to public (we'll add an access dropdown shortly)
    $referential->access_id = $access;
    //$decoded = json_decode($data, true);
    $referential->title = $title;
    // Set its description appropriately
    $referential->description = $description;
    // Before we can set metadata, we need to save the blog post
    if (!$referential->save()) {
      register_error(elgg_echo("pel:error"));
      $response['error'] = "Cannot save data !";
    }
    
    $referential->content = $data;
    
    $_SESSION['referentialGUID'] = $referential->guid;
    
    $response['guid'] = $referential->guid;
    $response['title'] = $referential->title;
    $response['description'] = $referential->description;
    // Success message
    system_message(elgg_echo("pel:saved"));
    // Remove the blog post cache
    unset($_SESSION['referentialData']);
    
    // envoi de la réponse au script
    header('Content-Type: application/json');
    echo json_encode($response);
  }
  
?>
